package com.gzxw.mogublog.xo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzxw.mogublog.commons.entity.Blog;
import com.gzxw.mogublog.commons.entity.SubjectItem;
import com.gzxw.mogublog.utils.StringUtils;
import com.gzxw.mogublog.xo.mapper.SubjectItemMapper;
import com.gzxw.mogublog.xo.service.BlogService;
import com.gzxw.mogublog.xo.service.SubjectItemService;
import com.gzxw.mogublog.xo.vo.SubjectItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SubjectItemServiceImpl extends ServiceImpl<SubjectItemMapper, SubjectItem> implements SubjectItemService {

    @Autowired
    private BlogService blogService;

    @Override
    public IPage<SubjectItem> getList(SubjectItemVO subjectItemVO) {
        QueryWrapper<SubjectItem> subjectItemQueryWrapper = new QueryWrapper<>();
        subjectItemQueryWrapper.eq("status", 1);
        subjectItemQueryWrapper.orderByDesc("sort");
        Page<SubjectItem> page = new Page<>();
        page.setCurrent(subjectItemVO.getCurrentPage());
        page.setSize(subjectItemVO.getPageSize());

        IPage<SubjectItem> pageList = this.page(page, subjectItemQueryWrapper);
        List<SubjectItem> records = pageList.getRecords();

        List<String> blogUids = new ArrayList<>();

        records.forEach(item -> {
            blogUids.add(item.getBlogUid());
        });
        if (blogUids.size() > 0) {
            Collection<Blog> blogList = blogService.listByIds(blogUids);
            if (blogList.size() > 0) {
                HashMap<String, Blog> blogMap = new HashMap<>();
                // TODO 设置标签分类以及图片
                blogList.forEach(item -> {
                    blogMap.put(item.getUid(), item);
                });
                records.forEach(item -> {
                    item.setBlog(blogMap.get(item.getBlogUid()));
                });
                pageList.setRecords(records);
            }
        }

        return pageList;
    }

    @Override
    public String addSubjectItem(List<SubjectItemVO> subjectItemVOList) {

        List<String> blogUidList = new ArrayList<>();
        String subjectUid = "";
        // 首先拿到Vo的全部博客id
        subjectItemVOList.forEach(item -> {
            blogUidList.add(item.getBlogUid());
            if (StringUtils.isEmpty(subjectUid) && StringUtils.isNotEmpty(item.getSubjectUid())) {
                blogUidList.add(item.getSubjectUid());
            }
        });
        // 查询SubjectItem中是否包含重复的博客
        QueryWrapper<SubjectItem> subjectItemQueryWrapper = new QueryWrapper<>();
        subjectItemQueryWrapper.eq("subject_uid", subjectUid);
        subjectItemQueryWrapper.in("blog_uid", blogUidList);
        subjectItemQueryWrapper.eq("status", 1);
        List<SubjectItem> repeatBlogList = this.list(subjectItemQueryWrapper);
        // 找出重复的博客UID
        List<String> repeatBlogUids = new ArrayList<>();
        repeatBlogList.forEach(item -> {
            repeatBlogUids.add(item.getBlogUid());
        });

        List<SubjectItem> subjectItemList = new ArrayList<>();
        for (SubjectItemVO subjectItemVO : subjectItemVOList) {
            if (StringUtils.isEmpty(subjectItemVO.getSubjectUid()) || StringUtils.isEmpty(subjectItemVO.getBlogUid())) {
                return "输入参数有误";
            }
            // 判断是否重复添加
            if (repeatBlogUids.contains(subjectItemVO.getBlogUid())) {
                continue;
            } else {
                SubjectItem subjectItem = new SubjectItem();
                subjectItem.setSubjectUid(subjectItemVO.getSubjectUid());
                subjectItem.setBlogUid(subjectItemVO.getBlogUid());
                subjectItem.setStatus(1);
                subjectItemList.add(subjectItem);
            }
        }
        if (subjectItemList.size() <= 0) {
            if (repeatBlogUids.size() == 0) {
                return "插入失败";
            } else {
                return "插入失败，有" + repeatBlogUids.size() + "个重复";
            }
        } else {
            this.saveBatch(subjectItemList);
            if (repeatBlogUids.size() == 0) {
                return "插入成功";
            } else {
                return "插入成功,已跳过" + repeatBlogUids.size() + "个重复数据";
            }
        }
    }

    @Override
    public String editSubjectItem(List<SubjectItemVO> subjectItemVOList) {
        List<String> subjectItemUidList = new ArrayList<>();
        subjectItemVOList.forEach(item -> {
            subjectItemUidList.add(item.getUid());
        });
        Collection<SubjectItem> subjectItems = null;
        if (subjectItemUidList.size() > 0) {

            subjectItems = this.listByIds(subjectItemUidList);
            if (subjectItems.size() > 0) {
                Map<String ,SubjectItemVO> subjectItemVOMap = new HashMap<>();
                subjectItemVOList.forEach(item-> {
                    subjectItemVOMap.put(item.getUid(),item);
                });
                // 修改排序字段
                subjectItems.forEach(item -> {
                    SubjectItemVO subjectItemVO = subjectItemVOMap.get(item.getUid());
                    item.setSubjectUid(subjectItemVO.getSubjectUid());
                    item.setBlogUid(subjectItemVO.getBlogUid());
                    item.setStatus(1);
                    item.setUpdateTime(new Date());
                    item.setSort(subjectItemVO.getSort());
                });
                this.updateBatchById(subjectItems);
            }
        }
        return "更新成功";
    }

    @Override
    public String deleteBatch(List<SubjectItemVO> subjectItemVOList) {

        if (subjectItemVOList.size()<=0) {
            return "参数有误!";
        }
        List<String > uids = new ArrayList<>();
        subjectItemVOList.forEach(item -> {
            uids.add(item.getUid());
        });
        this.removeByIds(uids);

        return "删除成功";
    }

    @Override
    public String sortByCreateTime(String subjectUid, Boolean isDesc) {
        QueryWrapper<SubjectItem> subjectItemQueryWrapper = new QueryWrapper<>();
        subjectItemQueryWrapper.eq("status",1);
        subjectItemQueryWrapper.eq("subject_uid",subjectUid);
        // 查询所有的专题列表
        List<SubjectItem> subjectItemList = this.list(subjectItemQueryWrapper);
        // 获取专题中的博客uid
        List<String > blogUidList = new ArrayList<>();
        subjectItemList.forEach(item -> {
            blogUidList.add(item.getBlogUid());
        });
        if (blogUidList.size() <=0) {
            return "更新失败";
        }
        // 通过uids查询博客
        Collection<Blog> blogList = blogService.listByIds(blogUidList);
        List<Blog> tempBlogList = new ArrayList<>();
        if(isDesc) {
            tempBlogList = blogList.stream().sorted(Comparator.comparing(Blog::getCreateTime).reversed()).collect(Collectors.toList());
        } else {
            tempBlogList = blogList.stream().sorted(Comparator.comparing(Blog::getCreateTime)).collect(Collectors.toList());
        }

        int maxSort = tempBlogList.size();
        Map<String, Integer> subjectItemSortMap = new HashMap<>();
        for (Blog item : tempBlogList) {
            subjectItemSortMap.put(item.getUid(), maxSort--);
        }
        for (SubjectItem subjectItem: subjectItemList) {
                subjectItem.setSort(subjectItemSortMap.get(subjectItem.getBlogUid()));
        }
        this.updateBatchById(subjectItemList);
        return "操作成功";
    }
}
